const db = require("../db/index");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config");

// 注册处理函数
exports.regUser = (req, res) => {
  const userInfo = req.body;
  //   if (!userInfo.username || !userInfo.password) {
  //     res.cc("用户名或密码不能为空");
  //   }
  const isUser = "select * from ev_users where username=?";
  db.query(isUser, [userInfo.username], (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 0) return res.cc("用户名已存在");
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);
    // 插入新用户语句
    const setUser = "insert into ev_users set ?";
    db.query(setUser, userInfo, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("注册失败");
      res.cc("注册成功", 0);
    });
  });
};
// 登录处理函数
exports.login = (req, res) => {
  const userInfo = req.body;
  const selectUser = "select * from ev_users where username=?";
  db.query(selectUser, [userInfo.username], (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("用户名不存在");
    const compareResult = bcrypt.compareSync(
      userInfo.password,
      results[0].password
    );
    if (!compareResult) return res.cc("密码错误");
    const user = { ...results[0], password: "", user_pic: "" };
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn, // token 有效期为 10 个小时
    });
    res.send({
      status: 0,
      message: "登录成功！",
      // 为了方便客户端使用 Token，在服务器端直接拼接上 Bearer 的前缀
      token: "Bearer " + tokenStr,
    });
  });
};
